<template>
  <div style="margin-bottom: 20px;">
    <el-dialog :title="edit_main_title" append-to-body v-dialogDrag :visible.sync="edit_flag"
               @open="handleOpenConfig" :before-close="handleClose">
      <el-row type="flex" justify="space-between" style="padding: 10px 0">
        <el-col>
          <el-input style="width: 180px" v-model="page.condition.name" @keyup.enter.native="search" placeholder="发运点"></el-input>
          <el-button type="primary" @click="search">查询</el-button>
        </el-col>
        <el-col style="text-align: right">
        </el-col>
      </el-row>
      <el-table key="1" ref="houseMultipleTable" :data="table_data" v-loading="loadingShow"
                element-loading-text="加载中" border fit highlight-current-row
                style="width: 99%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column align="center" label="序号" width="">
          <template slot-scope="scope">
            <span>{{scope.$index+1}}</span>
          </template>
        </el-table-column>
        <el-table-column width="200" align="center" label="编码">
          <template slot-scope="scope">
            <span>{{scope.row.code}}</span>
          </template>
        </el-table-column>
        <el-table-column width="140" align="center" label="名称">
          <template slot-scope="scope">
            <span>{{scope.row.name}}</span>
          </template>
        </el-table-column>
        <el-table-column width="120" align="center" label="所在省份">
          <template slot-scope="scope">
            <span>{{scope.row.province}}</span>
          </template>
        </el-table-column>
        <el-table-column width="120" align="center" label="所在城市">
          <template slot-scope="scope">
            <span>{{scope.row.city}}</span>
          </template>
        </el-table-column>
        <el-table-column width="120" align="center" label="所在区县">
          <template slot-scope="scope">
            <span>{{scope.row.county}}</span>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        style="margin-top: 8px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.current"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="page.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
      <el-row type="flex" justify="end">
        <el-button type="primary" @click="handleClose">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </el-row>
      <div style="height:20px"></div>
    </el-dialog>
  </div>
</template>

<script type="text/javascript">
  import * as SysUserApi from '@/api/sys/sysuser'
  export default {
    name: '',
    components: {
    },
    props: ['edit_flag', 'edit_main_title', 'edit_select_row', 'edit_params'],
    data() {
      return {
        title_data: {},
        loadingShow: false,
        selectRow: [],
        selectRowAll: [],
        selectAllIds: [], // 当前角色拥有的权限
        idKey: 'id', // 标识列表数据中每一行的唯一键的名称
        selectIds: [],
        page: {
          current: 1,
          size: 10,
          total: 0,
          condition: {
            name: ''
          }
        },
        haveReq: false,
        table_data: []
      }
    },
    created() {
    },
    methods: {
      handleOpenConfig(data) {
        this.table_data = []
        this.page = {
          current: 1,
          size: 10,
          total: 0,
          condition: { name: '' }
        }
        this.haveReq = false
        this.selectAllIds = []
        this.selectRowAll = []
        this.getList()
      },
      getList() {
        this.loadingShow = true
        SysUserApi.allUsableStoreHouse(this.page).then(res => {
          this.loadingShow = false
          const t = res.data
          this.table_data = t.records
          this.page.current = t.current
          this.page.size = t.size
          this.page.total = t.total
          if (!this.haveReq) {
            console.log('---getOwnerIds()----')
            this.getOwnerIds()
          } else {
            setTimeout(() => {
              this.setSelectRow()
            }, 50)
          }
        }).catch(() => {
          this.loadingShow = false
        })
      },
      // 表格改变时
      handleSelectionChange(val) {
        setTimeout(() => {
          this.changePageCoreRecordData(val)
        }, 50)
      },
      // 初始回填选中状态
      setSelectRow() {
        if (!this.selectAllIds || this.selectAllIds.length <= 0) {
          return
        }
        // 标识当前行的唯一键的名称
        const idKey = this.idKey
        this.$refs.houseMultipleTable.clearSelection()
        for (let i = 0; i < this.table_data.length; i++) {
          if (this.selectAllIds.indexOf(this.table_data[i][idKey]) >= 0) {
            // 设置选中，记住table组件需要使用ref="table"
            this.$refs.houseMultipleTable.toggleRowSelection(this.table_data[i], true)
            // // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
            // if (!this.hasPermissions(this.selectRowAll, this.table_data[i], idKey)) {
            //   this.selectRowAll.push(this.table_data[i])
            // }
          }
        }
        console.log('回填this.selectRowAll', this.selectRowAll)
      },
      // 判断数集内是否有该对象，有则返回 true，无则返回false
      hasPermissions(selectRowAll, item, key) {
        if (item && item[key]) {
          return selectRowAll.some(row => item[key] === row[key])
        } else {
          return true
        }
      },
      // 表格改变修改选中数据记录
      changePageCoreRecordData(val) {
        console.log('changePageCoreRecordData()----')
        console.log('初that.selectAllIds', this.selectAllIds)
        console.log('初this.selectRowAll', this.selectRowAll)
        console.log('初val', val)
        // 标识当前行的唯一键的名称
        const idKey = this.idKey
        const that = this
        if (val.length < 0) {
          return
        }
        const selectIds = []
        // 获取当前页选中的id
        val.forEach(row => {
          selectIds.push(row[idKey])
        })
        const init_arr = this.selectAllIds.concat(selectIds) // 数组合并
        this.selectAllIds = Array.from(new Set(init_arr)) // 数组去重
        const noSelectIds = []
        // 得到当前页没有选中的id
        this.table_data.forEach(row => {
          if (selectIds.indexOf(row[idKey]) < 0) {
            noSelectIds.push(row[idKey])
          }
        })
        noSelectIds.forEach(id => {
          if (this.selectAllIds.indexOf(id) >= 0) {
            for (let i = 0; i < that.selectAllIds.length; i++) {
              if (that.selectAllIds[i] === id) {
                // 如果总选择中有未被选中的，那么就删除这条
                that.selectAllIds.splice(i, 1)
                break
              }
            }
          }
        })
      },
      // 选中状态请求
      getOwnerIds() {
        SysUserApi.ownHouse(this.edit_select_row.id).then(response => {
          this.loadingShow = false
          this.selectAllIds = response.data
          this.haveReq = true
          this.setSelectRow()
        }).catch(() => {
          this.haveReq = false
          this.loadingShow = false
        })
      },
      // 查询
      search() {
        this.page.current = 1
        this.page.size = 10
        this.getList()
      },
      handleSizeChange(val) {
        this.page.size = val
        this.page.current = 1
        this.getList()
      },
      handleCurrentChange(val) {
        this.page.current = val
        this.getList()
      },
      // 确认
      confirmClick() {
        if (this.selectAllIds && this.selectAllIds.length > 0) {
          // this.checkOneSelect(this.selectRowAll)
          // const ids = []
          // this.selectRowAll.forEach(function(item, index, array) {
          //   ids.push(item.id)
          // })
          // console.log('提交的ids', ids)
          SysUserApi.grantHouse(this.edit_select_row.id, this.selectAllIds).then(response => {
            if (response.code === 0) {
              this.$notify({
                title: '成功',
                message: '仓库分配成功',
                type: 'success',
                duration: 2000
              })
              this.$refs.houseMultipleTable.clearSelection()
            } else {
              this.$notify({
                title: '失败',
                message: response.message,
                type: 'fail',
                duration: 2000
              })
            }
            this.$emit('edit-close', false)
          })
        } else {
          this.$message({
            message: '未选择',
            type: 'warning',
            duration: 2000
          })
        }
      },
      // 检查是否选择单条
      checkOneSelect(data) {
        const l = data.length
        if (l === 0) {
          this.$message({
            message: '未选择',
            type: 'warning',
            duration: 2000
          })
          return false
        }
        // if (l > 1) {
        //   this.$message({
        //     message: ' 不可多选, 请选择单条!',
        //     type: 'warning',
        //     duration: 2000
        //   })
        //   return false
        // }
        return true
      },
      handleClose() {
        this.$emit('edit-close', false)
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>
